<!-- 渠道配置 -->
<template>
	<div class="container">
		<!-- 搜索条件 -->
		<yd-form :options="formOptions" :model="formData" :btns="formBtns"></yd-form>

		<!--查询列表-->
		<YdTable
			ref="multipleTable"
			:formData="formData"
			:tableConfig="tableConfig"
			:tableData="tableData"
			@sizeChangeHandler="searchHandler"
			@currentChangeHandler="searchHandler"
			@sortChangeHandler="searchHandler"
			@selectionChangeHandler="handleSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog v-model="addDialogForm.open" :title="title" width="500px" append-to-body center :close-on-click-modal="false" @close="cancelHandle">
			<el-form ref="conForm" :model="form" :rules="rules" label-width="140px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="渠道编码:" prop="channelCode">
							<el-input
								v-model="form.channelCode"
								placeholder="请输入渠道编码"
								style="width: 200px"
								:readonly="addDialogForm.inputReadOnly"
								maxlength="20"
							/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="渠道名称:" prop="channelName">
							<el-input
								v-model="form.channelName"
								placeholder="请输入渠道名称"
								style="width: 200px"
								:readonly="addDialogForm.inputReadOnly"
								maxlength="20"
							/>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="系统名称:" prop="systemId">
							<el-select v-model="form.systemId" placeholder="请选择" style="width: 200px">
								<el-option v-for="(dict, index) in options.systemOptions" :key="index" :label="dict.label" :value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer class="dialog-footer">
				<el-button v-if="addDialogForm.showSubmit" type="primary" @click="submitForm">确 定</el-button>
				<el-button v-if="addDialogForm.showSubmit" @click="cancelHandle">取 消</el-button>
				<el-button v-if="addDialogForm.showClose" type="primary" @click="cancelHandle">关 闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="ChannelsConfig" lang="ts">
import { queryChannelList, queryChannelById, addChannel, editChannel, deleteChannelByIds } from '@/api/management/systemManage/channelsConfig';
import { queryAppSystemOptions } from '@/api/search/searchOptions';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { ref, reactive, toRefs, onMounted } from 'vue';

const { proxy } = useCurrentInstance();

// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 弹出层标题
const title = ref('');
// 表单参数
const data = reactive<anyObj>({
	form: {},
});
const { form } = toRefs(data);
const formOptions = reactive<FormOptionType>([
	{
		type: 'input',
		label: '渠道名称',
		prop: 'channelName',
		attrs: {
			clearable: true,
		},
	},
	{
		type: 'input',
		label: '渠道编码',
		prop: 'channelCode',
		attrs: {
			clearable: true,
		},
	},
]);
const formBtns = reactive<BtnType[]>([
	{
		type: 'primary',
		text: '查询',
		handler: searchHandler,
	},
]);
let addDialogForm = reactive({
	// 是否显示弹出层
	open: false,
	//是否显示确认提交按钮，查看详情的时候不需要确认按钮
	showSubmit: true,
	showClose: false,
	inputReadOnly: false,
});
//下拉框选项
let options = reactive<anyObj>({
	systemOptions: [],
});
// 网端表单校验
const rules = ref({
	channelCode: [{ required: true, message: '渠道编码不能为空', trigger: 'blur' }],
	channelName: [{ required: true, message: '渠道名称不能为空', trigger: 'blur' }],
	systemId: [{ required: true, message: '系统名称不能为空', trigger: 'change' }],
});
// 搜索表单数据
let formData = reactive<anyObj>({});
// 列表配置
let tableConfig = reactive({
	url: queryChannelList,
	columns: [
		{
			label: '渠道编码',
			prop: 'channelCode',
		},
		{
			label: '渠道名称',
			prop: 'channelName',
		},
		{
			label: '系统ID',
			prop: 'systemId',
		},
		{
			label: '系统名称',
			prop: 'systemName',
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['channelManagement:add'], handler: () => addHandle() },
		{ name: '修改', icon: 'yd-icon-edit', permi: ['channelManagement:edit'], disable: 'single', handler: () => updateHandle() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['channelManagement:delete'], disable: 'multiple', handler: () => deleteHandle() },
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 列表数据
let tableData = ref([]);
const conForm = ref<any>();

onMounted(() => {
	//查询系统
	queryAppSystemOptions().then((res: ApiResponse) => {
		const data = res.data;
		if (data !== null) {
			for (let i = 0; i < data.length; i++) {
				let temp: anyObj = {};
				temp.value = parseInt(data[i].value);
				temp.label = data[i].label;
				options.systemOptions.push(temp);
			}
		}
	});
	searchHandler();
});

// 搜索
function searchHandler() {
	tableConfig.loading = true;
	queryChannelList(formData).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy.$modal.msgError(res.msg);
			tableConfig.loading = false;
			return;
		}
		tableConfig.loading = false;
		tableData.value = res.data.records;
		tableConfig.pagination.total = res.data.total;
	});
}
// 多选框选中数据
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: anyObj) => item.id);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}
/** 新增按钮操作 */
function addHandle() {
	reset();
	title.value = '增加渠道';
	addDialogForm.open = true;
	//控制是否可以有提交按钮，详情不能有提交按钮
	addDialogForm.showSubmit = true;
	addDialogForm.showClose = false;
	addDialogForm.inputReadOnly = false;
}
/** 修改按钮操作 */
function updateHandle() {
	reset();
	title.value = '修改渠道';
	addDialogForm.open = true;
	//控制是否可以有提交按钮，详情不能有提交按钮
	addDialogForm.showSubmit = true;
	addDialogForm.showClose = false;
	addDialogForm.inputReadOnly = false;
	const id = ids.value;
	queryChannelById(id).then((response) => {
		const data = response.data;
		form.value = data;
	});
}
/** 删除按钮操作 */
function deleteHandle() {
	if (ids.value === null) {
		proxy.$modal.msgWarning('请选择要删除的渠道信息。');
		return;
	}
	proxy.$modal
		.confirm('是否删除已经勾选的渠道信息?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(() => {
			deleteChannelByIds(ids.value).then((response) => {
				if (response.code === 0) {
					addDialogForm.open = false;
					// 删除后的总条数
					let totalCount = tableConfig.pagination.total - ids.value.length;
					// 计算删除后的总页数
					let totalPage = Math.ceil(totalCount / tableConfig.pagination.pageSize);
					// 如果删除后的总页数小于1, 置为1
					totalPage = totalPage < 1 ? 1 : totalPage;
					// 判断删除前的页数是否大于删除后的总页数, 计算当前页应该是多少赋值给查询表单
					tableConfig.pagination.pageNum = tableConfig.pagination.pageNum > totalPage ? totalPage : tableConfig.pagination.pageNum;
					proxy.$modal.msgSuccess('删除成功');
					searchHandler();
				} else {
					proxy.$modal.msgWarning(response.msg);
					return;
				}
			});
		})
		.catch(function () {
			addDialogForm.open = false;
			proxy.$modal.msgSuccess('删除失败');
			searchHandler();
		});
}
/** 提交按钮 */
function submitForm() {
	conForm.value.validate((valid: any) => {
		if (valid) {
			if (form.value.id !== undefined) {
				editChannel(form.value).then((response) => {
					if (response.code === 0) {
						addDialogForm.open = false;
						proxy.$modal.msgSuccess('修改成功');
						searchHandler();
					} else {
						proxy.$modal.msgWarning(response.msg);
						return;
					}
				});
			} else {
				addChannel(form.value).then((response) => {
					if (response.code === 0) {
						addDialogForm.open = false;
						proxy.$modal.msgSuccess('新增成功');
						searchHandler();
					} else {
						proxy.$modal.msgWarning(response.msg);
						return;
					}
				});
			}
		}
	});
}
function cancelHandle() {
	addDialogForm.open = false;
	reset();
	// proxy.$forceUpdate();
}
// 表单重置
function reset() {
	form.value = {
		name: undefined,
	};
	conForm.value?.resetFields();
}
//查看详情
function getDetailHandle(row: anyObj) {
	title.value = '渠道详情';
	addDialogForm.open = true;
	//控制是否可以有提交按钮，详情不能有提交按钮
	addDialogForm.showSubmit = false;
	addDialogForm.showClose = true;
	addDialogForm.inputReadOnly = true;
	queryChannelById(row.id).then((response) => {
		const data = response.data;
		form.value = data;
	});
}
</script>

<style scoped>
.container {
	margin: 10px;
}
</style>
